package com.mmche.app.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.framework.base.util.Tool;
import com.framework.web.springmvc.BaseController;
import com.mmche.app.common.Constant;
import com.mmche.app.common.WeixinUtil;
import com.mmche.app.pojo.AccessToken;

/**
 * 微信相关服务
 * @author wjk
 *
 */
@Controller
public class WeixinController extends BaseController{

	
	
	/**
	 * 微信验证
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/weixin/token")
	public void token(HttpServletRequest request, HttpServletResponse response) throws IOException{
		 // 微信加密签名
        String signature = request.getParameter("signature");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        String[] str = { Constant.WX_TOKEN, timestamp, nonce };
        Arrays.sort(str); // 字典序排序
        String bigStr = str[0] + str[1] + str[2];
        // SHA1加密
        //String digest = new SHA1().getDigestOfString(bigStr.getBytes()).toLowerCase();
        String digest = DigestUtils.shaHex(bigStr);
        // 确认请求来至微信
        if (digest.equals(signature)) {
            response.getWriter().print(echostr);
        }
	}
	/**
	 * 微信验证
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping("/weixin/createMenu")
	public void createMenu(HttpServletRequest request, HttpServletResponse response){
		String user_define_menu = "{\"button\":[{\"type\":\"view\",\"name\":\"估价宝\",\"url\":\"" + Constant.EVALUATE_URL + "\"}]}";
		//此处改为自己想要的结构体，替换即可
		AccessToken accessToken= WeixinUtil.getAccessToken();
		System.out.println(accessToken);
		System.out.println(accessToken.getAccess_token());
		if(accessToken != null && !Tool.isEmpty(accessToken.getAccess_token())){
			String action = Constant.WX_CREATE_MENU + accessToken.getAccess_token();
			try {
			    URL url = new URL(action);
			    HttpURLConnection http = (HttpURLConnection) url.openConnection();    
			    http.setRequestMethod("POST");        
			    http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");    
			    http.setDoOutput(true);        
				http.setDoInput(true);
				System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
				System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
				http.connect();
				OutputStream os= http.getOutputStream();    
	            os.write(user_define_menu.getBytes("UTF-8"));//传入参数    
	            os.flush();
	            os.close();
	            InputStream is =http.getInputStream();
	            int size =is.available();
	            byte[] jsonBytes =new byte[size];
	            is.read(jsonBytes);
	            String message=new String(jsonBytes,"UTF-8");
	            System.out.println(message);
	     	}catch (MalformedURLException e) {
	     		logger.error("创建菜单出错",e);
	     	} catch (IOException e) {
	     		logger.error("创建菜单出错",e);
			}
		}
	}
}

